package com.liysh.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author liysh
 * @date 2021/7/23
 * @apiNote
 */
@Component
public class liyshBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        //在此方法内可以做任何操作
        if(beanName.equals("userService")){
            System.out.println("初始化前");
            ((UserServiceImpl)bean).setName("liyishan");
        }
       return bean;
    }

    @Override
    //正常进行AOP的地方
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化后");
        if(beanName.equals("userService")){
            //代理对象
            Object proxyInstance = Proxy.newProxyInstance(liyshBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //代理对象执行方法时先执行代理逻辑，然后通过反射执行对应的方法
                    System.out.println("代理逻辑");
                    method.invoke(bean,args);
                    return null;
                }
            });
            return proxyInstance;
        }

        return bean;
    }
}
